import Model from '../Model'
import {load_plist_img} from '../../common/utils'
import {AudioPlayer} from '../../common/audio/AudioPlayer'
import {AUDIO_CONFIG} from '../../service/Constant'


export enum EnumStatus {
    onReady = 0,
    onLand = 1,
    onFire = 2,
    onRemoved = 3
}

const {ccclass, property} = cc._decorator;

@ccclass
export default class BallItem extends cc.Component {

    @property(cc.Sprite)
    icon: cc.Sprite = null;

    @property(cc.Integer)
    type: number = 0;

    private _powerScale: number = 1
    private _status: EnumStatus = EnumStatus.onReady
    

    public get status() {
        return this._status
    }
    public set status(val) {
        this._status = val
        if(val == EnumStatus.onLand) {
            this.scheduleOnce(_ => {
                if(this.node && this.node.active) {
                    this.node.setPosition(Model.ins().ballInitX, Model.ins().ballInitY)
                    this.status = EnumStatus.onReady
                }
            }, 0)
        }
    }

    public get powerScale() {
        return this._powerScale;
    }
    public set powerScale(value) {
        this._powerScale = value;
        this.icon.node.setScale(value > 1 ? 1.5 : 1);
    }

    init(x: number, y: number, status: EnumStatus) {
        this.powerScale = 1
        this.node.x = x
        this.node.y = y
        this.status = status

        load_plist_img(this.icon, 'texture/plist/customize', `ball${0}`);
    }

    reset() {
        this.node.stopAllActions()
        this.status = EnumStatus.onRemoved
        this.getComponent(cc.RigidBody).linearVelocity = cc.v2(0, 0)
        this.powerScale = 1
        this.node.active = false
    }

    shoot(rotation: number) {
        const r = rotation * Math.PI / 180
        const speed = Model.ins().ballSpeed + 100 * Model.ins().ballFireSpeed
        const x= Math.sin(r) * speed
        const y = Math.cos(r) * speed
        this.getComponent(cc.RigidBody).linearVelocity = cc.v2(x, y).mul(2);
        this.status = EnumStatus.onFire
    }

    fireBall(fire_rotation: number) {
        const radians = fire_rotation * Math.PI / 180;
        const ball_speed = Model.ins().ballSpeed + 100 * Model.ins().ballFireSpeed;
        this.getComponent(cc.RigidBody).linearVelocity = cc.v2(Math.sin(radians) * ball_speed, Math.cos(radians) * ball_speed);
        this.status = EnumStatus.onFire;
    }

    onBeginContact(contact: cc.PhysicsContact, selfCollider: cc.PhysicsCollider, otherCollider: cc.PhysicsCollider) {
        switch (otherCollider.tag) {
            case 1: {
                // 触底
                if (this.node.active) {
                    this.getComponent(cc.RigidBody).linearVelocity = cc.v2(0, 0);
                    this.status = EnumStatus.onLand;
                }
                break;
            }
        }
    }
}
